const nodemailer = require('nodemailer');

class EmailService {
  constructor() {
    this.transporter = nodemailer.createTransport({
      host: process.env.SMTP_HOST,
      port: process.env.SMTP_PORT,
      secure: process.env.SMTP_SECURE === 'true',
      auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASS
      }
    });
  }

  async sendTestEmail(to) {
    try {
      const info = await this.transporter.sendMail({
        from: `"Deploy Platform" <${process.env.SMTP_USER}>`,
        to: to,
        subject: '测试邮件 - Deploy Platform',
        html: `
          <h2>邮件通知测试</h2>
          <p>这是一封测试邮件，用于验证邮件通知功能是否正常工作。</p>
          <p>如果您收到这封邮件，说明邮件通知功能已配置成功。</p>
        `
      });
      console.log('测试邮件发送成功:', info);
      return true;
    } catch (error) {
      console.error('发送测试邮件失败:', error);
      throw error;
    }
  }

  async sendPasswordChangeEmail(to) {
    try {
      const info = await this.transporter.sendMail({
        from: `"Deploy Platform" <${process.env.SMTP_USER}>`,
        to: to,
        subject: '密码已更改 - Deploy Platform',
        html: `
          <h2>密码更改通知</h2>
          <p>您的账号密码已被修改。</p>
          <p>如果这不是您本人的操作，请立即联系管理员。</p>
        `
      });
      console.log('密码更改通知邮件发送成功:', info);
      return true;
    } catch (error) {
      console.error('发送密码更改通知邮件失败:', error);
      throw error;
    }
  }

  async sendDeployNotification(to, project, status, logs) {
    try {
      const subject = `部署${status === 'success' ? '成功' : '失败'} - ${project.name}`;
      const info = await this.transporter.sendMail({
        from: `"Deploy Platform" <${process.env.SMTP_USER}>`,
        to: to,
        subject: subject,
        html: `
          <h2>部署通知</h2>
          <p>项目 <strong>${project.name}</strong> 的部署任务${status === 'success' ? '已完成' : '失败'}。</p>
          <h3>部署日志：</h3>
          <pre style="background:#f5f5f5;padding:10px;border-radius:4px">
${logs.map(log => `[${new Date(log.timestamp).toLocaleString()}] ${log.message}`).join('\n')}
          </pre>
        `
      });
      console.log('部署通知邮件发送成功:', info);
      return true;
    } catch (error) {
      console.error('发送部署通知邮件失败:', error);
      throw error;
    }
  }
}

module.exports = new EmailService(); 